package com.javasea.netty.tcp.simpleclient;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.timeout.IdleStateHandler;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

/**
 * https://blog.csdn.net/weixin_39753791/article/details/111683829?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1.no_search_link&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1.no_search_link
 */
public class HeartClient {
    private final String host;
    private final int port;


    public HeartClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void start() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group);
            b.channel(NioSocketChannel.class);
            b.remoteAddress(new InetSocketAddress(host, port));
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                	// 需要调用connect()方法来连接服务器端，但我们也可以通过调用bind()方法返回的ChannelFuture中获取Channel去connect服务器端。
//                    ch.pipeline().addLast(new IdleStateHandler(0, 10, 0, TimeUnit.SECONDS));

                    // 行拆包器，识别\n或者\r\n进行拆包。不能开启，否则下面的FixedLengthFrameDecoder失效
                    ch.pipeline().addLast(new LineBasedFrameDecoder(1024));

                    // 利用FixedLengthFrameDecoder解码器，无论一次接收到多少数据报，它都会按照构造函数中设置的固定长度进行解码，
                    // 如果是半包消息，FixedLengthFrameDecoder会缓存半包消息并等待下个包到达后进行拼包，直到读取到一个完整的包。
//                    ch.pipeline().addLast(new FixedLengthFrameDecoder(20));

                    // channelRead的msg自动转换成了String类型
                    ch.pipeline().addLast(new StringDecoder());
//                    ch.pipeline().addLast(new StringEncoder());
                    // 最后再将数据转到handler进行处理
                    ch.pipeline().addLast(new HeartClientHeartBeat(host + ":" + port));
                }
            });
            // serverSocketchannel的设置，链接缓冲池的大小
            b.option(ChannelOption.SO_BACKLOG, 2048);
            b.option(ChannelOption.SO_KEEPALIVE,true);
            //发起异步连接操作
            ChannelFuture f = b.connect().sync();
            f.addListener((ChannelFutureListener) future -> {
                if(future.isSuccess()){
                    System.out.println("client connected");
                }else{
                    System.out.println("server attemp failed");
                    future.cause().printStackTrace();
                }
            });
            //等待客户端链路关闭
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) {
        new Thread(() -> {
            try {
                new HeartClient("192.168.1.200", 2002).start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                new HeartClient("localhost", 2003).start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();

    }
}
